package com.hopedove.net.domain;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.hopedove.net.ErrResponse;
import com.hopedove.net.OkResponse;
import com.hopedove.net.RespParseUtil;
import com.hopedove.net.Response;
import com.hopedove.net.WebServiceUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class Communication {
    private static final String TAG = "Communication";
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    private final static ExecutorService executorService = Executors.newCachedThreadPool();

    public static void request(Request request, ResponseHandler handler) {
        String response = WebServiceUtil.request(request.getMethod(), request.getParams());
        Log.d(TAG, "req: " + request.getParams());
        Log.d(TAG, "resp: " + response);
        // 服务器返回的响应，有可能是 json 对象，也有可能是 json 数组
        Response resp = null;
        JSONObject jsonObject = null;
        try {
            if (RespParseUtil.isJsonArray(response)) {
                JSONArray array = new JSONArray(response);
                jsonObject = array.optJSONObject(0);
            } else if (RespParseUtil.isJsonObject(response)) {
                jsonObject = new JSONObject(response);
            } else {
                // 响应既不是 JSONArray 也不是 JSONObject，那么有可能是包含错误信息的普通文本
                resp = new ErrResponse(response);
            }

            if (jsonObject != null) {
                if (!RespParseUtil.isResponseOk(jsonObject)) {
                    resp = new ErrResponse(RespParseUtil.getMessage(jsonObject));
                } else {
                    resp = new OkResponse(response);
                }
            } else if (resp == null) {
                resp = new ErrResponse("数据解析异常");
            }
        } catch (JSONException e) {
            // ignore
            resp = new ErrResponse(e.toString());
        }

        final Response cbResp = resp;
        mainHandler.post(() -> handler.onResponse(cbResp));
    }

    public static void asyncRequest(Request request, ResponseHandler handler) {
        executorService.execute(() -> request(request, handler));
    }

    public static interface ResponseHandler {
        void onResponse(Response response);
    }

}
